<template>
  <div class="container">
    <!-- 提示区域 -->
    <div class="card_head">
      <span class="explain">说明：目前支持学科和关键字条件筛选</span>
      <el-button type="success" icon="el-icon-edit" size="small">新增试题</el-button>
    </div>
    <!-- 搜索区域 -->
    <el-form ref="form" :model="form" size="small" label-width="70px">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="学科" prop="subjectID">
            <el-select v-model="form.subjectID" placeholder="请选择" @change="selectList">
              <el-option
                v-for="item in subjects"
                :key="item.id"
                :label="item.subjectName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="二级目录" prop="catalogID">
            <el-select v-model="form.catalogID" placeholder="请选择">
              <el-option
                v-for="item in catalogs"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标签" prop="tags">
            <el-select v-model="form.tags" placeholder="请选择">
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.tagName"
                :value="item.tagName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="关键字" prop="keyword">
            <el-input v-model="form.keyword" placeholder="请根据题干选择"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="试题类型" prop="questionType">
            <el-select v-model="form.questionType" placeholder="请选择">
              <el-option
                v-for="item in questTy"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="难度" prop="difficulty">
            <el-select v-model="form.difficulty" placeholder="请选择">
              <el-option
                v-for="item in difficulty"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="方向" prop="direction">
            <el-select v-model="form.direction" placeholder="请选择">
              <el-option v-for="item in direction" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="录入人" prop="creatorID">
            <el-select v-model="form.creatorID" placeholder="请选择">
              <el-option
                v-for="item in creator"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="题目备注" prop="remarks">
            <el-input v-model="form.remarks"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="企业简称" prop="shortName">
            <el-input v-model="form.shortName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="城市" prop="province">
            <el-select
              v-model="form.province"
              placeholder="请选择"
              class="province"
            >
              <el-option
                v-for="item in citySelect.province"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select v-model="form.city" placeholder="请选择" class="city">
              <el-option
                v-for="item in citySelect.cityDate"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item class="btnClass">
            <el-button @click="resetForm('form')">清除</el-button>
            <el-button type="primary" @click="choiceData(form)">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 列表区域 -->
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待审核" name="to_audit"></el-tab-pane>
      <el-tab-pane label="已审核" name="checked"></el-tab-pane>
      <el-tab-pane label="已拒绝" name="refused"></el-tab-pane>
    </el-tabs>
    <div class="table_head">
      <i class="el-icon-info"></i>
      <span>
        数据一共
        <i>{{counts}}</i>
        条
      </span>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="number" label="试题编号" width="120"></el-table-column>
      <el-table-column prop="subject" label="学科" width="120"></el-table-column>
      <el-table-column prop="catalog" label="目录" width="120"></el-table-column>
      <el-table-column prop="questionType" label="题型" width="120"></el-table-column>
      <el-table-column v-html="tableData.question" label="题干" width="280">
        <template slot-scope="scope">
          <div v-html="scope.row.question"></div>
        </template>
      </el-table-column>
      <el-table-column prop="addDate" label="录入时间" :formatter="dateFormatter" width="180"></el-table-column>
      <el-table-column prop="difficulty" label="难度" width="80"></el-table-column>
      <el-table-column prop="creator" label="录入人" width="120"></el-table-column>
      <el-table-column prop="chkState" label="审核状态" width="120"></el-table-column>
      <el-table-column prop="chkRemarks" label="审核意见" width="150"></el-table-column>
      <el-table-column prop="chkUser" label="审核人" width="120"></el-table-column>
      <el-table-column prop="pubType" label="发布状态" width="150"></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click="previewClick(scope.$index,scope.row)" type="text" size="small">预览</el-button>
          <el-button
            @click="auditClick(scope.$index,scope.row)"
            type="text"
            size="small"
            :disabled="scope.row.chkState === '待审核' ? false : true"
          >审核</el-button>
          <el-button
            @click="modifyClick(scope.$index,scope.row)"
            type="text"
            size="small"
            :disabled="scope.row.publishState === 0 ? false : true"
          >修改</el-button>
          <el-button
            @click="putawayClick(scope.$index,scope.row)"
            type="text"
            size="small"
            v-if="scope.row.publishState === 0"
          >上架</el-button>
          <el-button
            @click="putawayClick(scope.$index,scope.row)"
            type="text"
            size="small"
            v-if="scope.row.publishState === 1"
          >下架</el-button>
          <el-button
            @click="delectClick(scope.$index,scope.row)"
            type="text"
            size="small"
            :disabled="scope.row.publishState === 0 ? false : true"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next, sizes, jumper"
      :total="counts"
      :page-size="form.pagesize"
      :page-sizes="[5, 10, 20, 50]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
    <!-- 审核窗口 -->
    <questions-check ref="checkForm" :dialogFlag.sync="checkDialogVisible" @checkContent="checkOk"></questions-check>
    <!-- 预览窗口 -->
    <questions-preview :dialogVisible.sync="viewDialogVisible" :details="details"></questions-preview>
  </div>
</template>

<script>
import { questionType as questTy, difficulty, publishType, checkType, direction, creator } from '@/api/hmmm/constants'
import { choice, remove, choicePublish, choiceCheck, detail } from '@/api/hmmm/questions'
import { list as sublist } from '@/api/hmmm/subjects'
import { list as dirlist } from '@/api/hmmm/directorys'
import { list as tagslist } from '@/api/hmmm/tags'
import { provinces, citys } from '@/api/hmmm/citys'
import QuestionsPreview from '../components/questions-preview'
import QuestionsCheck from '../components/questions-check'
export default {
  data () {
    return {
      form: {
        page: 1,
        pagesize: 5,
        subjectID: null,
        difficulty: null,
        questionType: null,
        tags: null,
        province: null,
        city: null,
        keyword: null,
        remarks: null,
        shortName: null,
        direction: null,
        creatorID: null,
        catalogID: null,
        chkState: null
      },
      tableData: [],
      activeName: 'all',
      counts: 0,
      // 学科列表
      subjects: [],
      // 二级目录
      catalogs: [],
      // 标签
      tags: [],
      // 试题类型
      questTy: [],
      // 难度
      difficulty: [],
      // 方向
      direction: [],
      // 录入人
      creator: [],
      // 省、市
      citySelect: {
        province: [],
        cityDate: []
      },
      checkDialogVisible: false,
      viewDialogVisible: false,
      details: [{ question: '', questionType: '', options: [], videoURL: '', answerID: '' }],
      curId: ''
    }
  },
  watch: {
    'form.province':{
      handler(newVal,oldVal){
        this.form.city =null
        this.handleProvince(newVal)
      }
    }
  },
  created () {
    this.choiceData(this.form)
    this.subList()
    this.initialize()
    this.getCityData()
  },
  methods: {
    // 格式化日期
    dateFormatter (row, column) {
      let datetime = row.addDate
      if (datetime) {
        datetime = new Date(datetime)
        const y = datetime.getFullYear()
        const m = this.padZero(datetime.getMonth() + 1)
        const d = this.padZero(datetime.getDate())
        const hh = this.padZero(datetime.getHours())
        const mm = this.padZero(datetime.getMinutes())
        const ss = this.padZero(datetime.getSeconds())
        return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
      }
      return ''
    },
    // 日期补'0'
    padZero (n) {
      return n > 9 ? n : '0' + n
    },
    // 学科列表
    async subList () {
      const { data: { items } } = await sublist({ pagesize: 50 })
      this.subjects = items
    },
    selectList () {
      this.dirList()
      this.tagsList()
    },
    // 目录列表
    async dirList () {
      const params = { subjectID: this.form.subjectID }
      const { data: { items } } = await dirlist(params)
      this.catalogs = items
    },
    // 标签列表
    async tagsList () {
      const params = { subjectID: this.form.subjectID }
      const { data: { items } } = await tagslist(params)
      this.tags = items
    },
    // 获取省
    getCityData: function () {
      this.citySelect.province = provinces()
    },
    // 选省获取到市
    handleProvince: function (e) {
      this.citySelect.cityDate = citys(e)
    },
    // 初始化变量
    initialize () {
      this.questTy = questTy
      this.difficulty = difficulty
      this.direction = direction
      this.creator = creator
    },
    // 清除选择项
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 精选题库列表
    async choiceData (params) {
      const { data } = await choice(params)
      data.items.forEach((item) => {
        item.questionType = questTy.filter(i => i.value.toString() === item.questionType)[0].label
        item.difficulty = difficulty.filter(i => i.value.toString() === item.difficulty)[0].label
        let pubType = 1
        if (item.chkState === 1) {
          pubType = item.publishState === 1 ? 2 : 3
        }
        item.pubType = publishType.filter(i => i.value === pubType)[0].label
        item.chkState = checkType.filter(i => i.value === item.chkState)[0].label
      })
      this.tableData = data.items
      this.counts = data.counts
    },
    // 切换标签页
    handleClick (tab, event) {
      if (tab.index > 0) {
        this.form.chkState = tab.index - 1
      } else {
        this.form.chkState = null
      }
      this.choiceData(this.form)
    },
    // 分页跳转
    handleSizeChange (val) {
      this.form.pagesize = val
      this.choiceData(this.form)
    },
    // 分页跳转
    handleCurrentChange (val) {
      this.form.page = val
      this.choiceData(this.form)
    },
    // 点击预览按钮
    async previewClick (index, row) {
      const params = {
        id: row.id
      }
      try {
        const { data } = await detail(params)
        this.viewDialogVisible = true
        this.details = [data]
      } catch (error) {
        this.$message.error('试题数据获取失败!')
      }
    },
    // 点击审核按钮
    auditClick (index, row) {
      this.checkDialogVisible = true
      this.curId = row.id
    },
    // 审核题目
    async checkOk (params) {
      const data = params
      data.id = this.curId
      try {
        await choiceCheck(data)
        this.choiceData(this.form)
        this.checkDialogVisible = false
        this.$message.success('审核成功!')
      } catch (error) {
        this.$message.error('审核失败!')
      }
    },
    // 点击修改按钮
    modifyClick (index, row) {

    },
    // 点击上下架按钮
    putawayClick (index, row) {
      const pubState = row.publishState === 0 ? '上架' : '下架'
      this.$confirm(`您确定${pubState}这道题目吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 上下架题目
        const params = { id: row.id, publishState: (row.publishState === 0 ? 1 : 0) }
        await choicePublish(params)
        this.choiceData(this.form)
        this.$message({
          type: 'success',
          message: `${pubState}成功!`
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: `已取消${pubState}`
        })
      })
    },
    // 点击删除
    delectClick (index, row) {
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 删除精选题库
        const params = { id: row.id }
        await remove(params)
        this.choiceData(this.form)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  },
  components: {
    QuestionsCheck,
    QuestionsPreview
  }
}
</script>

<style scoped lang='less'>
.container {
  background-color: #fff;
  margin: 10px;
  padding: 15px;
  .card_head {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .explain {
      font-size: 12px;
      color: pink;
    }
  }
  .table_head {
    font-size: 13px;
    height: 30px;
    width: 100%;
    color: #909399;
    background-color: #f4f4f5;
    padding: 8px 16px;
    margin-bottom: 15px;
    .el-icon-info {
      margin-right: 5px;
    }
  }
  .el-select {
    width: 100%;
  }
  .btnClass {
    float: right;
  }
  .city {
    width: 48%;
  }
  .province {
    width: 48%;
    margin-right: 4%;
  }
  .el-pagination {
    text-align: right;
    margin-top: 20px;
  }
  i {
    font-style: normal;
  }
}
/deep/.el-dialog__footer {
  text-align: right;
}
</style>
